<template>
  <div class="weather_container" style="background-color: #a1a1a1">
    <!-- 导航栏 -->
    <div class="nav_wthr">
      <!-- 左边引用element的el-select组件以及el-button组件实现城市切换 -->
      <div class="serch_wthr">
        <el-select
          v-model="input"
          filterable
          :filter-method="inputHandler"
          @change="selecedChange(input)"
          placeholder="请选择城市"
        >
          <!-- 在el-select组件内用v-for指令循环渲染cities数组中存的城市列表 -->
          <el-option
            v-for="item in citiesList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left">{{ item.label }}</span>
            <!-- el-icon实现删除功能 -->
            <i
              class="el-icon-delete"
              style="float: right; line-height: 100%"
              @click="removeCity(item.value)"
            ></i>
          </el-option>
        </el-select>
        <!-- 如果是新的城市，切换的同时添加到cities数组中 -->
        <el-button type="primary" @click="addCityWthr">切换</el-button>
      </div>
      <!-- 外层包裹一个固定宽度的盒子，防止fullTime未渲染时，前一个盒子在flex布局时出现跳动 -->
      <div class="timebox">
        <div class="nav_time" v-if="this.time.year">{{ fullTime }}</div>
      </div>
    </div>
    <!-- 当前气温显示栏 -->
    <div class="td_wthr">
      <div class="wthr_box">
        <div class="wthr_box_city">{{ wthr.city }}</div>
        <div class="temp">{{ wthr.hours[0].tem }}℃</div>
        <div class="temp_hl">{{ wthr.tem1 }} / {{ wthr.tem2 }} ℃</div>
        <div class="wthr_air">{{ wthr.wea }} | {{ wthr.air_level }}</div>
      </div>
    </div>
    <!-- 24小时天气 -->
    <div class="hour_wthr">
      <!-- 利用v-for指令循环渲染每小时天气 -->
      <div
        v-for="(item, i) in wthr.hours.slice(1)"
        :key="i"
        class="hour_wthr_item"
      >
        <div class="hour_wthr_item_time">
          {{ item.hours }}
        </div>
        <div class="hour_wthr_item_wea">
          <img
            class="wthr_icon"
            :src="require('../assets/weaicons/' + item.wea_img + '.png')"
          />
        </div>
        <div class="hour_wthr_item_tem">{{ item.tem }}℃</div>
      </div>
    </div>
    <!-- 一周天气 -->
    <div class="days_whtr">
      <div
        v-for="(item, index) in futureWthr.data"
        :key="index"
        class="days_whtr_item"
      >
        <div class="days_wthr_date">{{ item.date.slice(5) }}</div>
        <div class="days_wthr_week">{{ item.week }}</div>
        <img
          class="wthr_icon"
          :src="require('../assets/weaicons/' + item.wea_img + '.png')"
        />
        <p class="days_wthr_wea_text">{{ item.wea }}</p>
        <div class="days_wthr_tem">{{ item.tem1 }} / {{ item.tem2 }} ℃</div>
        <div class="days_wthr_air">{{ item.air_level }}</div>
      </div>
    </div>
    <!-- 天气指数 -->
    <div class="wthr_index">
      <div class="wthr_index_env">
        <div class="wthr_index_table">天气指数</div>
        <div class="wthr_index_env_container">
          <div v-for="(item, i) in wthrIndex" :key="i" class="wthr_index_item">
            <img
              :src="require('../assets/indexicons/' + item.index_img + '.png')"
            />
            <div class="wthr_index_data">{{ item.index }}</div>
            <div class="wthr_index_name">{{ item.index_name }}</div>
          </div>
        </div>
      </div>
      <div class="wthr_index_air">
        <div class="wthr_index_table">空气质量</div>
        <div class="wthr_index_air_container">
          <div class="wthr_index_air_icon" :style="apiBgc">
            <div class="wthr_index_air_level">{{ wthr.aqi.air_level }}</div>
            <div class="wthr_index_air_num">{{ wthr.aqi.air }}</div>
          </div>
          <div class="wthr_index_air_tips">
            当前空气质量指数为：{{ wthr.aqi.air }}<br />
            {{ wthr.aqi.air_tips }}
          </div>
        </div>
      </div>
      <div class="wthr_index_env">
        <div class="wthr_index_table">生活指数</div>
        <div class="wthr_index_env_container">
          <div v-for="(item, i) in liveIndex" :key="i" class="wthr_index_item">
            <img
              :src="require('../assets/indexicons/' + item.index_img + '.png')"
            />
            <div class="wthr_index_data">{{ item.index }}</div>
            <div class="wthr_index_name">{{ item.index_name }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
// 引入axios
import request from '../Apis/request.js'

import { mapState, mapMutations } from 'vuex'
export default {
  name: 'weather',
  data() {
    return {
      // 输入栏绑定值
      input: '',

      time: {
        year: 0,
        mon: 0,
        dat: 0,
        hour: 0,
        min: 0,
        sec: 0,
      },
      // 定时器
      timer: null,

      // 天气指数
      wthrIndex: [],
      // 生活指数
      liveIndex: [],
    }
  },
  methods: {
    // 利用mapMutations引入VueX中更新状态的方法
    ...mapMutations('m_wthr', [
      'updateWthr',
      'updateTime',
      'updateFutureWthr',
      'updateCitiesList',
    ]),
    // 获取时间
    getTime() {
      clearTimeout(this.timer)
      const date = new Date()

      this.time.year = date.getFullYear()
      this.time.mon = date.getMonth() + 1
      this.time.dat = date.getDate()
      this.time.hour =
        date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      this.time.min =
        date.getMinutes() < 10
          ? '0' + this.date.getMinutes()
          : date.getMinutes()
      this.time.sec =
        date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      this.timer = setTimeout(this.getTime, 1000)
    },
    // 利用axios请求天气数据
    async getWthr(city) {
      // 防抖
      if (Date.now() - this.lastUpTime >= 3000 && city !== '') {
        const res = await request.get(
          'https://v0.yiketianqi.com/api?unescape=1&version=v62&appid=68879182&appsecret=Laz2mexq',
          {
            params: {
              city: city,
            },
          }
        )
        const res1 = await request.get(
          'https://v0.yiketianqi.com/api?unescape=1&version=v91&appid=68879182&appsecret=Laz2mexq',
          {
            params: {
              city: city,
            },
          }
        )
        if (res.status === 200) {
          // 用res.data更新VueX中的状态
          this.updateWthr(res.data)
          this.updateFutureWthr(res1.data)
          // 获取最新的天气指数
          this.getIndex()

          this.updateTime(Date.now())
          // 判断cities数组中是否有当前城市，如果没有，就添加
          console.log('ok')
          if (this.citiesList.length === 0 || !this.inList()) {
            console.log(this.citiesList)
            this.addCityToList()
          }
        } else {
          alert('请输入正确的城市')
        }
      }
    },
    // 获取天气指数
    getIndex() {
      this.wthrIndex = [
        {
          index_name: '体感温度',
          index: this.wthr.tem || 'no data',
          index_img: 'tem',
        },
        {
          index_name: '紫外线',
          index: this.wthr.zhishu.ziwaixian.level || 'no data',
          index_img: 'urv',
        },
        {
          index_name: '风力',
          index: this.wthr.win_speed || 'no data',
          index_img: 'wds',
        },
        {
          index_name: '风向',
          index: this.wthr.win || 'no data',
          index_img: 'wdf',
        },
      ]
      this.liveIndex = [
        {
          index_name: '钓鱼',
          index: this.wthr.zhishu.diaoyu.level || 'no data',
          index_img: 'fish',
        },
        {
          index_name: '晨练',
          index: this.wthr.zhishu.chenlian.level || 'no data',
          index_img: 'chenlian',
        },
        {
          index_name: '穿衣指数',
          index: this.wthr.zhishu.chuanyi.level || 'no data',
          index_img: 'chuanyi',
        },
        {
          index_name: '感冒',
          index: this.wthr.zhishu.ganmao.level || 'no data',
          index_img: 'ganmao',
        },
        {
          index_name: '洗车',
          index: this.wthr.zhishu.xiche.level || 'no data',
          index_img: 'xiche',
        },
      ]
    },
    // 切换城市
    addCityWthr() {
      this.getWthr(this.input)
    },
    // 删除城市
    removeCity(index) {
      var temp = this.citiesList
      var removeInedx = temp.findIndex((item) => item.value === index)
      temp.splice(removeInedx, 1)
      this.updateCitiesList(temp)
    },
    // 自定义el-select搜索方法
    inputHandler(val) {
      this.input = val
    },
    // 选中已有城市，将input的值改为对应的label
    selecedChange(value) {
      this.citiesList.forEach((item) => {
        if (item.value === value) {
          this.input = item.label
        }
      })
    },
    // 添加城市
    addCityToList() {
      var newCity = {
        value: this.wthr.cityid,
        label: this.wthr.city,
      }
      var temp = this.citiesList
      temp.push(newCity)
      this.updateCitiesList(temp)
    },
    // 判断该城市是否在cities数组中
    inList() {
      var result = false

      this.citiesList.forEach((item) => {
        if (item.label === this.wthr.city) result = true
      })
      return result
    },
  },
  computed: {
    // 引入m_wthr模块中的state
    ...mapState('m_wthr', ['wthr', 'lastUpTime', 'futureWthr', 'citiesList']),
    // 根据空气指数切换不同的颜色
    apiBgc() {
      switch (this.wthr.air_level) {
        case '优':
          return 'background-color: #01e801'
        case '良':
          return 'background-color: #fefe00'
        case '轻度污染':
          return 'background-color: #ff7e01'
        case '中度污染':
          return 'background-color: #fe0000'
        case '重度污染':
          return 'background-color: #99004a'
        case '严重污染':
          return 'background-color: #7d0122'
      }
    },
    // 动态拼接时间字符
    fullTime() {
      return (
        this.time.year +
        '年' +
        this.time.mon +
        '月' +
        this.time.dat +
        '日' +
        this.time.hour +
        ':' +
        this.time.min +
        ':' +
        this.time.sec
      )
    },
  },
  created() {
    this.getWthr('嘉定')
    this.getIndex()
  },
  mounted() {
    // console.log(this.timer)
    // this.timer = setTimeout(this.getTime(), 1000)
    this.timer = setTimeout(this.getTime, 1000)
    // this.getPosition()

    console.log(this.wthr)
    console.log(this.futureWthr)
  },
}
</script>
<style lang="less">
.weather_container {
  background-color: #217abc;
  background-size: 24rem;
}
.wthr_icon {
  width: 0.6rem;
}
.nav_wthr {
  line-height: 0.5rem;
  font-size: 0.225rem;
  color: #fff;
  height: 0.5rem;
  background-color: rgba(241, 243, 244, 0.3);

  display: flex;
  justify-content: space-between;
  .serch_wthr {
    width: 3.75rem;
    display: flex;
    justify-content: space-between;
    margin-left: 1.25rem;
  }
  .timebox {
    width: 3rem;
  }
}

.td_wthr {
  height: 3.75rem;

  display: flex;
  align-items: center;
  justify-content: space-around;
  .wthr_box {
    color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;

    .wthr_box_city {
      font-size: 0.25rem;
      font-weight: bold;
    }
    .temp {
      font-size: 0.9375rem;
    }
    .temp_hl {
      font-size: 0.2rem;
    }
    .wthr_air {
      font-size: 0.2rem;
      margin-top: 0.125rem;
    }
  }
}
.hour_wthr {
  color: #fff;
  height: 1.875rem;
  margin: 0.25rem;
  background-color: rgba(241, 243, 244, 0.3);
  border-radius: 10px;
  box-shadow: 0.0375rem 0.0375rem 0.0625rem transparent;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 0.1875rem 0;
  .hour_wthr_item {
    display: flex;
    justify-content: space-around;
    align-items: center;
    flex-direction: column;

    .hour_wthr_item_time {
      font-size: 0.15rem;
    }
    .hour_wthr_item_tem {
      font-size: 0.175rem;
    }
  }
}
.days_whtr {
  height: 2.5rem;
  margin: 0.25rem;
  background-color: rgba(241, 243, 244, 0.3);
  border-radius: 10px;
  color: #fff;
  display: flex;
  justify-content: space-around;
  align-items: center;
  text-align: center;
  .days_whtr_item {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    .days_wthr_date {
      font-size: 0.2rem;
    }
    .days_wthr_week {
      font-size: 0.175rem;
    }
    .days_wthr_wea_text {
      font-size: 0.175rem;
    }
    .days_wthr_tem {
      font-size: 0.2rem;
    }
    .days_wthr_air {
      font-size: 0.15rem;
    }
  }
}
.wthr_index {
  height: 2.5rem;
  margin: 0.25rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 0.25rem;
  color: #fff;
  .wthr_index_env {
    height: 100%;
    width: 30%;
    background-color: rgba(241, 243, 244, 0.3);
    border-radius: 10px;
    .wthr_index_table {
      font-size: 0.175rem;
      margin-left: 0.1875rem;
      height: 0.75rem;
      line-height: 0.75rem;
    }
    .wthr_index_env_container {
      display: flex;
      justify-content: space-around;
      align-items: center;
      height: 1.75rem;
      .wthr_index_item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-around;
        .wthr_index_data {
          font-size: 0.125rem;
        }
        .wthr_index_name {
          font-size: 0.15rem;
        }
      }
    }
  }
  .wthr_index_air {
    width: 30%;
    background-color: rgba(241, 243, 244, 0.3);
    height: 100%;
    border-radius: 10px;
    color: #fff;
    .wthr_index_table {
      font-size: 0.175rem;
      margin-left: 0.1875rem;
      height: 0.75rem;
      line-height: 0.75rem;
    }
    .wthr_index_air_container {
      display: flex;
      justify-content: space-around;
      height: 1.75rem;
      align-items: center;
      .wthr_index_air_icon {
        width: 1rem;
        height: 1rem;
        border-radius: 0.625rem;
        // background-color: #01e801;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
        .wthr_index_air_level {
          font-size: 0.15rem;
        }
        .wthr_index_air_num {
          font-size: 0.125rem;
        }
      }
      .wthr_index_air_tips {
        font-size: 0.15rem;
      }
    }
  }
  .wthr_index_live {
    width: 30%;
    background-color: rgba(241, 243, 244, 0.3);
    border-radius: 10px;
  }
}
</style>
